import enums from '@/common/sysEnum.js';
import api from '@/common/api.js'
import {wxAPI} from '@/common/wxApi.js'
import graceChecker from '@/common/graceChecker.js';

/**
 * 公用方法
 * @auth zengdd
 */
var Fly = require("flyio/dist/npm/wx"); //请求拦截器
var fly = new Fly;

let mixin = {
    data() {
        return {
            formIdArr: []
        };
    },
    methods: {
        /**
         * 授权 微信登录系
         */
        loginSystem() {
            let that = this;
            // 获取缓存的sessionKey
            let sessionKey = this.$store.getters.getSessionKey
            if (graceChecker.stringIsNullOrEmpty(sessionKey)) {
                that.getWxLogin();
            } else {
                // 如果sessionKey存在，则调用微信小程序的session_key有效性校验接口
                wxAPI(enums.enums.OPERTTYPE.WEIXIN_CHECK_SESSION).then(res => { //状态为fulfilled时执行
                    let userInfo = that.$store.getters.getUserInfo;
                    // 检出用户信息是否为null
                    if (graceChecker.stringIsNullOrEmpty(userInfo)) {
                        wxAPI(enums.enums.OPERTTYPE.WEIXIN_SETTING).then(res => {
                            if (!res.authSetting['scope.userInfo']) {
                                //测试环境用此方法
                                /* 				uni.navigateTo({
                                                        url: '/pages/demand/wxAuth'
                                                }); */
                                uni.reLaunch({
                                    url: '/pages/demand/wxAuth'
                                });
                                // 调用授权 授权成功后获取用户资料
                                /*
                                           wxAPI(enums.enums.OPERTTYPE.WEIXIN_AUTHORIZE).then(res => {
                                               console.log('8:授权成功，调用获取用户信息')
                                               that.getUserInfo();
                                           }) */
                            } else {
                                that.getUserInfo();
                            }
                        })
                    }
                }, function (e) { //状态为rejected时执行
                    that.getWxLogin()
                })
            }
        },
        /**
         * 调用微信登录 并调用api login方法获取sessionkey
         */
        getWxLogin() {
            let that = this;
            // 调微信登录方法
            wxAPI(enums.enums.OPERTTYPE.WEIXIN_LOGIN).then(res => {
                // 如果code不为null 则调用后台方法
                if (res.code) {
                    that.getSessionKey(res.code)
                } else {
                    console.log("code没有获取到")
                }
            })
        },
        /**
         * 获取sessionKey
         * @param code 微信小程序login api 返回的数据
         */
        getSessionKey(code) {
            let that = this;
            api.httpUNIReques('/wechat/login', {code: code}, enums.enums.REQUEST_METHOD.GET, null).then(res => {
                that.$store.dispatch('update_session_key', res.data.result.sessionKey); // 缓存sessionKey
                that.$store.dispatch('update_open_id', res.data.result.openId); // 缓存openId
                //存储成功后，调用登陆方法，将微信用户信息也存入本地中
                that.loginSystem();

            })
        },
        // 获取微信用户信息及系统用户信息
        getUserInfo() {
            let that = this;
            return new Promise(function (resolve, reject) {  //增加异步处理陈志杰 2018-12-29
                // 获取微信用户资料
                wxAPI(enums.enums.OPERTTYPE.WEIXIN_USER_INFO).then(res => { //获取成功执行
                    uni.setStorageSync(enums.enums.USER.WX_USER_INFO, res); // 缓存微信用户信息
                    let sessionKey = that.$store.getters.getSessionKey;//获取缓存中sessionKey
                    let data = {
                        encryptedData: res.encryptedData,
                        iv: res.iv
                    };
                    // 请求后台接口
                    api.httpUNIReques('/wechat/getUserInfo', data, enums.enums.REQUEST_METHOD.GET, sessionKey).then(res => {
                        that.$store.dispatch('update_user_info', res.data.result); // 缓存openId
                        resolve(true);
                    })
                }).catch(function(e){   //获取不成功
					 resolve(false);
			   });
            })

        },
        /**
         * 微信支付功能
         * /陈志杰 增加params参数,增加Promise方法解决异步调用问题
         */
        wxPayment(demandId) {
            // 登录UNI
            return new Promise(function (resolve, reject) {
                uni.login({
                    success: (e) => {
                        api.httpRequest('/wechat/demand/unifiedOrder?demandId=' + demandId, null, enums.enums.REQUEST_METHOD.POST).then(res => {
                            if (res.code === 200) {
                                let paymentData = res.result;
                                uni.requestPayment({
                                    timeStamp: paymentData.timestamp,
                                    nonceStr: paymentData.nonceStr,
                                    package: paymentData.packAge,
                                    signType: 'MD5',
                                    paySign: paymentData.sign,
                                    success: (res) => {
                         /*               uni.showToast({
                                            title: "付款成功!"
                                        }) */
                                        resolve(paymentData);
                                    },
                                    fail: (res) => {
										if(res.errMsg=='requestPayment:fail cancel'){
											uni.showModal({
												content: "支付失败,原因为: 用户取消支付!" ,
												showCancel: false
											})
										}else{
											uni.showModal({
												content: "支付失败,原因为: " + res.errMsg,
												showCancel: false
											})
										}
                            
                                    },
                                    complete: () => {
                                      //  this.loading = false;
                                    }
                                })
                            } else {
                                uni.showModal({
                                    content: "支付失败，请重试！",
                                    showCancel: false
                                });
                                return;
                            }
                        })
                    }
                })
            })
        },
        /**
         * 保存FormId入库
         * @author 曾丁丁
         * @param e
         */
        commonSaveFormId(e) {
            let that = this;
            let formId = e.detail.formId;
            this.collectFormIds(formId); //保存推送码
            if (that.formIdArr.length === 6) {
                var params = {
                    formId: JSON.stringify(that.formIdArr)
                };
                api.httpRequest('/wechat/saveFormId', params, enums.enums.REQUEST_METHOD.POST).then(res => {
                })
            }
        },
        /**
         * 保存推送码
         * @author zengdd
         * @param formId
         */
        collectFormIds: function (formId) {
            let that = this;
            let formIds = that.formIdArr;  // 获取全局推送码数组
            if (!formIds) {
                formIds = [];
            }
            let data = {
                formId: formId,
                expire: new Date().getTime() + 60480000  // 7天后的过期时间戳
            }
            formIds.push(data);
            that.formIdArr = formIds;
        },
        /**
         * 显示消息提示框
         * @param message 提示的消息
         * @param duration 持续时间（ms 默认3000ms）
         */
        showToast(message, duration) {
            uni.showToast({
                title: message,
                icon: 'none',
                duration: !duration ? 3000 : duration
            });
        },
        /**
         * 显示error提示信息
         * @param msg
         * @param duration
         */
        showError(msg, duration) {
            if (!msg) { // 如果message为空则过滤掉
                return;
            }
            uni.showToast({
                title: msg,
                icon: 'none',
                duration: !duration ? 3000 : duration
            });
        },
        /**
         * 跳转页面
         * @param url 跳转页面路径
         */
        goTo(url) {
            uni.navigateTo({
                url: url
            });
        },
        /**
         * 获取分享的标题
         * @returns {string}
         */
        getShareTitle: function () {
            let userInfo = this.$store.getters.getUserInfo;
            let wxUserInfo = this.$store.getters.getWXUserInfo;
            var title = wxUserInfo && wxUserInfo.nickName ? wxUserInfo.nickName : (userInfo && userInfo.wxNickName ? userInfo.wxNickName : '');
//				title += '向你发送了货单';
            title = title === '' ? '' : title + '向你发送了求购';

            return title;
        },

        /**
         * 拨号或者查看报价
         * @param data {Object} 求购信息
         */
        callQouteFn(data) {
            let that = this;
            if (data.isPay || data.isSelf) {  //如果已经支付，就直接拨打电话
				var url = '/wechat/demand/callDemandOwner?demandId='+data.id;
				var params = {};
				api.httpRequest(url, params, "POST").then((res) => {  //电话联系接口
				   if(res.code==200){
					    uni.makePhoneCall({
					       phoneNumber: data.contactMobileNo //调用电话号码
					    });
				   }else{
					    uni.showToast({
					       title: res.message,
					       icon: 'none',
					       duration: 2000
					    });
				   }
		
				});

            } else {    //如果未支付弹出对话框
                var url = '/wechat/demand/getMoney';
                var params = {};
                api.httpRequest(url, params, "GET").then((res) => {  //获取支付金额
                    that.unreadQuote = res.result;   //获取报价金额
                    that.demandInfo = data;      //求购信息
                    that.isShowpayBox = true;  //弹出支付弹窗口
                });
            }
        },
        /**
         * 初始化小红点
         * @param index  {string} 小红点位置
         * POST /wechat/demand/getUnreadQuote
         */
        initTabBarBadge(index) {
            let that = this;
            var url = '/wechat/demand/getUnreadQuote'
            api.httpRequest(url, null, "POST").then((res) => {  //获取支付金额
                if (res.code !== 200) {
                    return;
                }
                that.$store.dispatch('update_unread_quote', res.result); // 缓存是否有报价信息
                if (res.result) {   //如果结果为true为有新的报价
                    that.TabBarBadge(index, true);
                } else {
                    that.TabBarBadge(index, false);
                }
            });
        },
        /**
         * 小红点样式展示
         * 小红点处理函数 index 为选项序号，依次从0向右边数，show为是否显示,true为显示
         * @param index  {string} 小红点位置
         * @param show  {boolean } true 显示  false不显示
         * POST /wechat/demand/getUnreadQuote
         */
        TabBarBadge(index, show) {
            if (show) {
                uni.showTabBarRedDot({
                    index: index,
                })
            } else {
                uni.hideTabBarRedDot({
                    index: index,
                })
            }
        },

    }

};
export default mixin;